package generation

import (
	"embed"
	"html/template"
	"os"
	"path/filepath"
	"strings"
)

const (
	packagedocker = "docker"
	packagek8s    = "k8s"
)

//go:embed release_tpl/*
var templates embed.FS

type AutoCodeService struct{}

func (autoCodeService *AutoCodeService) CreatePackageTemp(projectName, port, namespace, directory, types, giturl, viewName string) (string, error) {
	basePath := filepath.Join(directory, "release")

	templatePaths := []string{

		// docker线上部署配置
		packagedocker + "/prod/deploy.sh",
		packagedocker + "/prod/docker-compose.yml",

		// 镜像构建配置
		packagedocker + "/Dockerfile",
		packagedocker + "/buildUpload.sh",
		packagedocker + "/env.sh",

		// k8s chart配置更改
		packagek8s + "/cluster/custom-server.sh",

		// k8s 开发helm配置
		packagek8s + "/cluster/dev/deploy.sh",
		packagek8s + "/cluster/dev/values.yaml",

		// k8s 预发helm配置
		packagek8s + "/cluster/pre/deploy.sh",
		packagek8s + "/cluster/pre/values.yaml",

		// k8s 线上helm配置
		packagek8s + "/cluster/prod/deploy.sh",
		packagek8s + "/cluster/prod/values.yaml",
		packagek8s + "/cluster/prod/grayscale.sh",

		// Jenkins配置
		// "Jenkinsfile",

		// Jenkins 后端xml配置
		"config_backend.xml",

		// Jenkins 前端xml配置
		"config_node.xml",
	}

	data := struct {
		ProjectName string
		Port        string
		Namespace   string
		Types       string
		GitURL      string
	}{
		projectName,
		port,
		namespace,
		types,
		giturl,
	}

	for _, path := range templatePaths {
		fullPath := filepath.Join(basePath, path)
		if err := createAndWriteTemplate(templates, path, fullPath, data.Types, data); err != nil {

			return "", err
		}
	}

	// jenkinsURL := "http://mind-jenkins.im30.lan"

	// user := "sinuo"
	// apiToken := "1159220fd638981bada2e8bb81d4088601"

	// xmlName := "config_backend.xml"
	// if types == "node" {
	// 	xmlName = "config_node.xml"
	// }

	// configXML, err := os.ReadFile("release" + "/" + xmlName)
	// if err != nil {
	// 	fmt.Println("Error reading config.xml:", err)
	// 	return "Jenkins视图创建失败", err
	// }

	// createJob(jenkinsURL, user, apiToken, projectName, viewName, configXML)

	// Jenkins视图创建成功后删除临时xml
	os.Remove(basePath + "/config_backend.xml")
	os.Remove(basePath + "/config_node.xml")

	return "项目: (" + projectName + ") release自动化配置已生成于 " + basePath, nil
}

func createAndWriteTemplate(fs embed.FS, tmplPath, outputPath, types string, data interface{}) error {
	dir := filepath.Dir(outputPath)
	if err := os.MkdirAll(dir, 0777); err != nil {
		return err
	}

	file, err := os.OpenFile(outputPath, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0777)
	if err != nil {
		return err
	}
	defer file.Close()

	embedPath := "release_tpl/" + tmplPath
	tmpl, err := template.ParseFS(fs, embedPath)
	if err != nil {
		return err
	}

	// 根据types参数动态调整模板执行的数据
	var tmplData interface{}
	switch types {
	case "backend":
		tmplData = struct {
			Types string
			Data  interface{}
		}{
			Types: "Backend",
			Data:  data,
		}
	case "node":
		tmplData = struct {
			Types string
			Data  interface{}
		}{
			Types: "NodeJS",
			Data:  data,
		}
	}

	return tmpl.Execute(file, tmplData)
}

func (autoCodeService *AutoCodeService) CleanPackageTemp() (string, error) {
	jenkinsfilePath := "./release/Jenkinsfile"
	b, err := os.ReadFile(jenkinsfilePath)
	if err != nil {
		return "没有需要清理的release", nil
	}

	name := strings.Split(strings.Split(string(b), "name = ")[1], " ")[0]
	name = strings.Trim(name, "\"")

	if err := os.RemoveAll("./release"); err != nil {
		return "release文件夹删除失败", err
	}

	return "项目: (" + name + ") release自动化配置已清理", nil
}
